package com.shouhuobao.take.verify;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.baidu.location.BDLocation;
import com.iseastar.alipay.PayResult;
import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.app.Intents;
import com.iseastar.guojiang.app.WebViewActivity;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.logic.AppHttp;
import com.iseastar.guojiang.logic.JSON;
import com.iseastar.guojiang.model.ReqResult;
import com.iseastar.guojiang.model.UserBean;
import com.shb.model.OrderPayBean;
import com.shb.model.WxPayModel;
import com.shouhuobao.station.R;
import com.shouhuobao.station.wxapi.WXPayEntryActivity;
import com.shouhuobao.take.BaseActivityWithScroll;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import droid.frame.utils.Android;
import droid.frame.utils.android.MathUtils;
import droid.frame.view.TextWatcherExt;

/**
 * Created by joker on 2017/9/15.
 * 开通驿站收银台activity
 */
public class VerifyOrderPayActivity extends BaseActivityWithScroll implements View.OnClickListener {
    private final int SDK_PAY_FLAG = 1;
    private final int SDK_CHECK_FLAG = 2;

    private int type;//标注从初级驿站、标准驿站、专业驿站进入  0 初级驿站 1 标准驿站 2 专业驿站
    private String stationName1 = "入门级驿站";
    private String stationName2 = "标准级驿站";
    private String stationName3 = "专业级驿站";
    private String quoteCost = "0.00";//未进行抵扣钱的金额
    private String realCost = "0.00";//实际支付的金额
    private TextView mStationExpandCodeTV;//输入推广码
    private LinearLayout mExpandCodeLL;//费用明细中推广码减去的金额布局
    private TextView mExpandCodePriceTV;//推广码金额
    private TextView mPayMoneyTV;//实际需要支付金额
    //支付方式
    private CheckBox mAliPayCB, mWXPayCB;
    private String payMoneyHtmlStr = "<font color=#FFFFFF>实付款：</font><font color=#FDD120>%1$s</font><font color=#FFFFFF>元</font>";
    private BroadcastReceiver wxCallBack;
    private String currentCityName = "";//当前城市名字
    private String expandCodeStr = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setScrollHeight(100);
        type = getIntent().getIntExtra("type", 0);
        quoteCost = getIntent().getStringExtra("quoteCost");
        realCost = quoteCost;
        wxCallBack = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                showLoadingDialog(null);
                AppHttp.getInstance().stationOpenPayCallBack(AppCache.getOrderId(), 1);
            }
        };
        IntentFilter intentFilter = new IntentFilter("station_open_wxpay_callback");
        registerReceiver(wxCallBack, intentFilter);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.activity_verify_pay);
        super.findViewById();
        getAppTitle().setCommonTitle("收银台");
        mStationExpandCodeTV = (TextView) findViewById(R.id.station_expand_code_et);
        mExpandCodeLL = (LinearLayout) findViewById(R.id.expand_code_LL);
        mExpandCodePriceTV = (TextView) findViewById(R.id.expand_code_price_tv);
        mPayMoneyTV = (TextView) findViewById(R.id.verify_pay_money_tv);
        findViewById(R.id.get_expand_code_tv).setOnClickListener(this);
        //支付方式
        findViewById(R.id.pay_ali_layout).setOnClickListener(this);
        mAliPayCB = (CheckBox) findViewById(R.id.pay_ali_checkBox);
        findViewById(R.id.pay_wx_layout).setOnClickListener(this);
        mWXPayCB = (CheckBox) findViewById(R.id.pay_wx_checkBox);
        mAliPayCB.setChecked(true);
        //立即支付
        findViewById(R.id.verify_pay_tv).setOnClickListener(this);
        mStationExpandCodeTV.addTextChangedListener(new TextWatcherExt() {
            @Override
            public void afterTextChanged(Editable editable) {
                if (isNotEmpty(editable.toString().trim()) && editable.toString().trim().length() == 10 && isNotEmpty(currentCityName)) {
                    Android.hideSoftInput(getContext());
                    expandCodeStr = editable.toString();
                    showLoadingDialog(null);
                    AppHttp.getInstance().queryPromotionData(editable.toString(), type, currentCityName);
                } else {
                    realCost = quoteCost;
                    expandCodeStr = "";
                    mPayMoneyTV.setText(Html.fromHtml(String.format(payMoneyHtmlStr, realCost)));
                    mExpandCodeLL.setVisibility(View.GONE);
                }
            }
        });
        mPayMoneyTV.setText(Html.fromHtml(String.format(payMoneyHtmlStr, quoteCost)));
        TextView stationNameTV = (TextView) findViewById(R.id.station_type_name_tv);
        TextView stationPriceTV = (TextView) findViewById(R.id.station_type_price_tv);
        if (type == 1) {
            stationNameTV.setText(stationName1);
        } else if (type == 2) {
            stationNameTV.setText(stationName2);
        } else {
            stationNameTV.setText(stationName3);
        }
        stationPriceTV.setText("¥" + quoteCost);
        showLoadingDialog(null);
        Intents.startBaiduLocation(getContext(), null);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //支付宝支付
            case R.id.pay_ali_layout:
                mAliPayCB.setChecked(true);
                mWXPayCB.setChecked(false);
                break;
            //微信支付
            case R.id.pay_wx_layout:
                mAliPayCB.setChecked(false);
                mWXPayCB.setChecked(true);
                break;
            //立即支付  先进性订单请求
            case R.id.verify_pay_tv:
                if (isNotEmpty(realCost) && Double.parseDouble(realCost) > 0) {
                    payMoneyType();
                }
                break;
            //如何获得推广码？
            case R.id.get_expand_code_tv:
                Intent intent = new Intent(getContext(), WebViewActivity.class);
                intent.putExtra("title", "获得推广码");
                startActivity(intent);
                break;
        }
    }

    @Override
    public boolean handleMessage(final Message msg) {
        switch (msg.what) {
            case MsgID.location_baidu:// 获取位置
                cancelLoadingDialog();
                BDLocation mBdLocation = (BDLocation) msg.obj;
                if (mBdLocation != null) {
                    currentCityName = mBdLocation.getCity();
                }
                return false;
            //查询推广码价格
            case MsgID.station_query_promotion_code:
                cancelLoadingDialog();
                final ReqResult<?> result = JSON.parserMap(msg.obj, String.class);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(result) && result.getResultMap() != null && result.getResultMap().size() > 0) {
                            String value = result.getResultMap().get("value") + "";
                            if (isNotEmpty(value)) {
                                mExpandCodeLL.setVisibility(View.VISIBLE);
                                mExpandCodePriceTV.setText("-" + value + "元");
                                double price = MathUtils.sub(quoteCost, value);
                                if (price <= 0) {
                                    price = 0.01;
                                }
                                realCost = String.valueOf(price);
                                mPayMoneyTV.setText(Html.fromHtml(String.format(payMoneyHtmlStr, realCost)));
                            } else {
                                expandCodeStr = "";
                                mExpandCodeLL.setVisibility(View.GONE);
                                showToast("数据有误");
                            }
                        } else {
                            expandCodeStr = "";
                            mExpandCodeLL.setVisibility(View.GONE);
                            showToast(result.getMessage());
                        }
                    }
                });
                return true;
            //下完订单后进行回调  1 微信  2支付宝
            case MsgID.station_open_order:
                cancelLoadingDialog();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (mAliPayCB.isChecked()) {
                            final ReqResult<?> orderResult = JSON.parserMap(msg.obj.toString(), String.class);
                            if (checkLoginStatus(orderResult) && orderResult.getResultMap() != null && orderResult.getResultMap().size() > 0) {
                                AppCache.setOrderId(orderResult.getResultMap().get("orderId") + "");
                                alipay(orderResult.getResultMap().get("payInfo") + "");
                            } else {
                                showToast(orderResult.getMessage());
                            }
                        } else {
                            final ReqResult<WxPayModel> orderResult = JSON.parser(msg.obj, WxPayModel.class);
                            if (orderResult.isSuccess()) {
                                WxPayModel wxModel = orderResult.getResult();
                                if (wxModel == null) {
                                    showToast("数据有误");
                                    return;
                                }
                                AppCache.setOrderId(wxModel.getOrderId());
                                OrderPayBean pay = new OrderPayBean(wxModel);
                                handleWxpay(pay);
                            } else {
                                showToast(orderResult.getMessage());
                            }
                        }
                    }
                });
                return true;
            //微信或支付宝支付成功后回调
            case MsgID.wxPayCallback:
                cancelLoadingDialog();
                final ReqResult<?> wxReqResult = JSON.parser(msg.obj);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (checkLoginStatus(wxReqResult)) {
                            UserBean userBean = AppCache.getUser();
                            if (userBean != null) {
                                userBean.setLevel(type * 9);
                                AppCache.setUser(userBean);
                            }
                            setResult(Activity.RESULT_OK);
                            startActivity(VerifyPayResultActivity.class);
                            finish();
                        } else {
                            showToast(wxReqResult.getMessage());
                        }
                    }
                });
                return true;
            default:
                return super.handleMessage(msg);
        }

    }

    /**
     * 支付的类型
     */
    private void payMoneyType() {
        //支付宝支付
        if (mAliPayCB.isChecked()) {
            showLoadingDialog(null);
            AppHttp.getInstance().stationOpenOrder(2, quoteCost, realCost, type, expandCodeStr);
        } else {//微信支付
            final IWXAPI wxapi = WXAPIFactory.createWXAPI(this, null);
            if (wxapi.isWXAppInstalled() == false) {
                showToast("未安装微信");
                return;
            }
            showLoadingDialog(null);
            AppHttp.getInstance().stationOpenOrder(1, quoteCost, realCost, type, expandCodeStr);
        }
    }

    /**
     * * 处理跳转到微信支付
     * * @param pay
     */
    private void handleWxpay(OrderPayBean pay) {
        if (pay == null) {
            Toast.makeText(this, "订单数据异常", Toast.LENGTH_SHORT).show();
        } else {
            sendPayReq(pay);
        }
    }

    private void sendPayReq(OrderPayBean pay) {
        WXPayEntryActivity.payFrom = 11;
        IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
        msgApi.registerApp(pay.getAppid());
        //
        PayReq req = new PayReq();
        if (getIntent() != null) {
            String isCollect = getIntent().getStringExtra("isCollect");
            if (isCollect != null) {
                req.extData = isCollect;
            }
        }
        req.appId = pay.getAppid();
        req.partnerId = pay.getPartnerid();
        req.prepayId = pay.getPrepayid();
        req.packageValue = pay.getPackageValue();
        req.nonceStr = pay.getNoncestr();
        req.timeStamp = pay.getTimestamp();
        req.sign = pay.getSign();
        //
        msgApi.sendReq(req);
    }

    private Handler mPayHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    // String resultInfo = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(getContext(), "支付成功", Toast.LENGTH_SHORT).show();
                        AppHttp.getInstance().stationOpenPayCallBack(AppCache.getOrderId(), 2);
                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(VerifyOrderPayActivity.this, "支付结果确认中", Toast.LENGTH_SHORT).show();
                        }
                        // 6001代表支付取消
                        if (TextUtils.equals(resultStatus, "6001")) {

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(VerifyOrderPayActivity.this, "支付失败，请重试！", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                }
                case SDK_CHECK_FLAG: {
                    Toast.makeText(VerifyOrderPayActivity.this, "检查结果为：" + msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void alipay(final String payInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(getContext());
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mPayHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    protected void onDestroy() {
        if (wxCallBack != null) {
            unregisterReceiver(wxCallBack);
        }
        super.onDestroy();
    }
}
